package com.lina.controller.utils;

import io.jsonwebtoken.*;


import java.util.Date;
import java.util.UUID;

/**
 * JWT工具类
 */
public class JwtUtil {
    private static long time =1000* 60 * 60 * 1;
    private static String sign ="admin";

    public static String createToken(){
        JwtBuilder jwtBuilder= Jwts.builder();
        //jwToken -> abc.def.xyz
        String jwtToken = jwtBuilder
                //Header:头部
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                // Poyload 载荷
                .claim("username","tom")
                .claim("role","admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + time))//Token的过去时间
                .setId(UUID.randomUUID().toString()) //id字段
                //Sign:签名
                .signWith(SignatureAlgorithm.HS256,sign) //设置加密算法和签名
                // 使用"."连接成一个完整的字符串
                .compact();
        System.out.println(jwtToken);
        return jwtToken;
    }

    // 验证JWT
    public static boolean checkJwt(String token){
        return Jwts.parser().isSigned(token);
    }

    // 解析JWT
    public static void parseJwt(){
            String token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2OTc0MzUwMjAsImp0aSI6IjEwMzE2YzAxLWJmMGMtNDgyMi05NTE0LWUxYTA3MmJjM2U5NCJ9.YNNiHJ1hJ3fuGTuy-UZYa7lPGPy5-r07iHMu0ecqxTs";
            JwtParser jwtParser =Jwts.parser(); //获取JWT的解析对象
        //将Jwt转换成一个key-value的值，通过key来获取对应的value 获取jws对象中的数据：get(key) 获取value
        Jws<Claims> claimsJws = jwtParser.setSigningKey(sign).parseClaimsJws(token);
            Claims body = claimsJws.getBody();//存储的是用户保存的数据
            System.out.println(body.get("username"));
            System.out.println(body.get("role"));
            System.out.println(body.getId());
            System.out.println(body.getSubject());
            System.out.println(body.getExpiration());
    }

    public static void main(String[] args) {
//        createToken();
        parseJwt();
    }
}
